//
//  QFViewController.m
//  DouBan
//
//  Created by xubo on 14-2-14.
//  Copyright (c) 2014年 xubo. All rights reserved.
//

#import "QFViewController.h"
#import "DataBaseSimple.h"

#import "QFCell.h"
@interface QFViewController ()<UITableViewDataSource,UITableViewDelegate,NSURLConnectionDataDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *searchTextField;
- (IBAction)goSearch:(id)sender;
@property (weak, nonatomic) IBOutlet UITableView *bookTableView;
@property (weak, nonatomic) IBOutlet UIActivityIndicatorView *myAIV;
-(void)changeJson;
@end

@implementation QFViewController{
    NSMutableArray *_bookArray;
    NSMutableData *_netData;
    
    DataBaseSimple * _dataBase;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

/*
 didSelect .. 置位Read状态 写入数据库 刷新UI
 cellForRow.. 判断Read标志 决定显示红或者黑
 */

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    _bookArray=[NSMutableArray array];
    _netData=[NSMutableData data];
    
    [self.bookTableView registerNib:[UINib nibWithNibName:@"QFCell" bundle:Nil] forCellReuseIdentifier:@"xibCell"];
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 1)];
    view.backgroundColor=[UIColor greenColor];
    self.bookTableView.tableFooterView=view;
    self.searchTextField.delegate=self;
    

    [self performSelectorInBackground:@selector(readDataBase) withObject:nil];
//    [self funA];
//    [self funB];
    // 起一个后台线程
//    [self performSelectorInBackground:@selector(funA) withObject:nil];
//    [self performSelectorInBackground:@selector(funB) withObject:nil];
}

// 在主线程中运行
- (void)updateUI
{
    [self.bookTableView reloadData];
}

// 在ios开发中 子线程不要操作UI 通知主线程刷新UI
// 子线程运行该段代码
- (void)readDataBase
{
    _dataBase = [DataBaseSimple sharedDataBase];
    [_bookArray addObjectsFromArray:[_dataBase selectAllDataFromDataBase]];
    // 通知主线程
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
}

- (void)funA
{
    [NSThread sleepForTimeInterval:10.0];
    NSLog(@"A...");
}

- (void)funB
{
    NSLog(@"B...");
}

#pragma mark--
#pragma mark 自定义函数
-(void)changeJson{
    NSLog(@"xxx3");
    NSError *error;
    NSDictionary *books=[NSJSONSerialization JSONObjectWithData:_netData options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"error is %@",error);
    NSLog(@"xxx4");
    NSArray *bookArray=books[@"books"];
    NSLog(@"xxx5");
    [_bookArray removeAllObjects];
    
//    int i = 0;
    // 使用多线程
    [self performSelectorInBackground:@selector(writeDataBase:) withObject:bookArray];
    // 不使用多线程
//    for (NSDictionary *dic in bookArray) {
//        QFBookModel *model=[[QFBookModel alloc]initWithDic:dic];
//        [_bookArray addObject:model];
//        
//        // 创建数据库 创建表 4个字段 1个主键 ID Text BookName Text BookSummary Text 存数据库
//        [_dataBase insertDataToDataBase:model andKey:model.bookID.integerValue];
////        i++;
//    }
//    [self.bookTableView reloadData];
    [self.myAIV stopAnimating];
}

- (void)writeDataBase:(NSArray *)bookArray
{
    for (NSDictionary *dic in bookArray) {
        QFBookModel *model=[[QFBookModel alloc]initWithDic:dic];
        [_bookArray addObject:model];
        
        // 创建数据库 创建表 4个字段 1个主键 ID Text BookName Text BookSummary Text 存数据库
        [_dataBase insertDataToDataBase:model andKey:model.bookID.integerValue];
        //        i++;
    }
    
    [self performSelectorOnMainThread:@selector(updateUI) withObject:nil waitUntilDone:YES];
}

#pragma mark--
#pragma mark tableview代理方法
//一共多少组
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;//默认是1
}
//每组多少行
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return  _bookArray.count;
}
//每行多高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 113;
}
//返回每行的cell
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    QFCell *cell=[tableView dequeueReusableCellWithIdentifier:@"xibCell"];
    QFBookModel *model=_bookArray[indexPath.row];
    [cell refreshUIWithModel:model];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    QFBookModel * model = _bookArray[indexPath.row];
    model.bookRead = @"1";
    [_dataBase updateDataFromDataBase:model andKey:model.bookID.integerValue];
//    [self updateUI];
    [_bookArray replaceObjectAtIndex:indexPath.row withObject:model];
    QFCell * cell = (QFCell *)[tableView cellForRowAtIndexPath:indexPath];
    [cell refreshUIWithModel:model];
}

- (IBAction)goSearch:(id)sender {
    [self.searchTextField resignFirstResponder];
    NSString *baseString=@"https://api.douban.com/v2/book/search?";
    NSString *searchWord=self.searchTextField.text;
    NSString *flitWord=@"fields=id,title,summary";
    NSString *urlString=[NSString stringWithFormat:@"%@q=%@&%@",baseString,searchWord,flitWord];
    NSLog(@"url:%@",urlString);
    urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"url:%@",urlString);
    NSURLRequest *request=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
    [NSURLConnection connectionWithRequest:request delegate:self];
    [self.myAIV startAnimating];
}
#pragma mark--
#pragma mark nsurlconnetion代理方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    NSLog(@"xxxx0");
    _netData.length=0;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
     NSLog(@"xxxx1");
    [_netData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
     NSLog(@"xxxx2");
    [self changeJson];
    NSLog(@"string");
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self goSearch:Nil];
    return YES;
}
@end
